﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Linq.Expressions;
using AL.DAL.Core;

namespace AL.BLL {

    public abstract class ServiceBase<T> where T : class {

        protected IRepository<T> _Repository;

        public bool ProxyCreationEnabled {
            get {
                return _Repository.ProxyCreationEnabled;
            }
            set {
                _Repository.ProxyCreationEnabled = value;
            }
        }


        /// <summary>
        /// HH: 基于 IEnumerable 的基础分页方法（单个条件，排序传入字段的字符串）
        /// </summary>
        public IEnumerable<T> PageList(string orderBy, bool isAsc, Expression<Func<T, bool>> where, int pageIndex, int pageSize, out int rowsCount) {
            _Repository.ProxyCreationEnabled = false;
            return _Repository.PageList(orderBy, isAsc, where, pageIndex, pageSize, out rowsCount);
        }


        /// <summary>
        /// HH: 基于 IEnumerable 的基础分页方法（单个条件）
        /// </summary>
        public IEnumerable<T> PageList<TKey>(Expression<Func<T, TKey>> orderBy, bool isAsc, Expression<Func<T, bool>> where, int pageIndex, int pageSize, out int rowsCount) {
            _Repository.ProxyCreationEnabled = false;
            return _Repository.PageList(orderBy, isAsc, where, pageIndex, pageSize, out rowsCount);
        }
        // 单条件分页查询的用法演示
        //var list = _UserService.PageList( o => o.UserName, true, o => o.UserName == "HAVENT", 1, 10, out rowsCount);

        /// <summary>
        /// HH: 基于 IEnumerable 的基础分页方法（多个条件）
        /// </summary>
        public PagedResult<T> PageList<TKey>(Expression<Func<T, TKey>> orderBy, bool isAsc, List<Expression<Func<T, bool>>> where, int pageIndex, int pageSize) {
            _Repository.ProxyCreationEnabled = false;
            PagedResult<T> pList = new PagedResult<T>();
            int rowsCount;
            var list = _Repository.PageList(orderBy, isAsc, where, pageIndex, pageSize, out rowsCount);

            if (list != null) {
                pList.Results = list.ToList();
            }
            pList.TotalRowsCount = rowsCount;
            pList.PageSize = pageSize;
            pList.CurrentPage = pageIndex;
            pList.PageCount = (int)Math.Ceiling(pList.TotalRowsCount / (double)pList.PageSize);

            return pList;
        }

    }
}
